﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace AAPCVM
{
    public static class FileManager
    {
        private static string _applicationDirectory = AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Candidates";
        
        public static void PrepareXMLFromCSV()
        {
            String line;
            StreamReader sr = null;
            XmlDocument XD = new XmlDocument();
            string xmlFilePath = _applicationDirectory + "\\candidates.xml";
            try
            {
                if (File.Exists(xmlFilePath))
                    return;

                XmlNode Root = XD.AppendChild(XD.CreateElement("Root"));
         
                string filepath = _applicationDirectory + "\\Candidates.csv";

                //Pass the file path and file name to the StreamReader constructor
                sr = new StreamReader(filepath,Encoding.UTF8,false);

                //Read the first line of text
                line = sr.ReadLine();
                
                //Continue to read until you reach end of file
                while (line != null)
                {
                    AppendCandidateInfo(XD, Root, line);
                    line = sr.ReadLine();
                }

                XD.Save(xmlFilePath);
                sr.Close();

            }
            catch (Exception e)
            {
            }
            finally
            {
                sr = null;
            }
        }

        private static void AppendCandidateInfo(XmlDocument doc, XmlNode root, string row)
        {
            string[] list = row.Split(',');

            XmlNode Child = root.AppendChild(doc.CreateElement("Candidates"));

            XmlAttribute candidateName = Child.Attributes.Append(doc.CreateAttribute("Name"));
            candidateName.InnerText = list[1];

            XmlAttribute candidateAge = Child.Attributes.Append(doc.CreateAttribute("Age"));
            candidateAge.InnerText = list[2];

            XmlAttribute candidateVotes = Child.Attributes.Append(doc.CreateAttribute("Votes"));
            candidateVotes.InnerText = "0";

            Child.InnerText = list[0];
        }


        private static string GetCandidateInfoInCSV(XmlNode node)
        {
            string id = node.InnerText;
            string name = node.Attributes["Name"].Value;
            string age = node.Attributes["Age"].Value;
            string votes = node.Attributes["Votes"].Value;

            return id + "," + name + ',' + age + ',' + votes;
            
        }
        public static void PrepareResultsFile()
        {
            StreamWriter sw = null;
            try
            {
                string resultsFilepath = _applicationDirectory + "\\Results.csv";
                string xmlFilePath = _applicationDirectory + "\\candidates.xml";


                XmlDocument doc = new XmlDocument();
                doc.Load(xmlFilePath);

                //Pass the filepath and filename to the StreamWriter Constructor
                sw = new StreamWriter(resultsFilepath);

                XmlNodeList all = doc.GetElementsByTagName("Candidates");

                for (int i = 0; i < all.Count; i++)
                {
                    string candidateinfo = GetCandidateInfoInCSV(all[i]);
                    sw.WriteLine(candidateinfo);
                }

                sw.Flush();
                
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                //Close the file
                sw.Close();
                sw = null;
            }
        }

        public static Candidate[] IncreaseVotes(string[] CandidateId)
        {
            Candidate[] candidates = new Candidate[CandidateId.Length];
            string xmlFilePath = _applicationDirectory + "\\candidates.xml";

            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFilePath);
            var candidateInfo = doc.GetElementsByTagName("Candidates");

            for (int i = 0; i < CandidateId.Length; i++)
            {
                for (int j = 0; j < candidateInfo.Count; j++)
                {
                    if (CandidateId[i] == candidateInfo[j].InnerText)
                    {
                        string noOfVotes = candidateInfo[j].Attributes["Votes"].Value;
                        int votes = int.Parse(noOfVotes);
                        votes++;
                        candidateInfo[j].Attributes["Votes"].Value = votes.ToString();


                        Candidate newCandidate = new Candidate(candidateInfo[j].InnerText, candidateInfo[j].Attributes["Name"].Value);
                        candidates[i] = newCandidate;
                        break;
                    }
                }
            }
            doc.Save(xmlFilePath);

            return candidates;
        }
        public static void DecreaseVotes(string[] CandidateId)
        {

            string xmlFilePath = _applicationDirectory + "\\candidates.xml";

            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFilePath);
            var candidateInfo = doc.GetElementsByTagName("Candidates");

            for (int i = 0; i < CandidateId.Length; i++)
            {
                for (int j = 0; j < candidateInfo.Count; j++)
                {
                    if (CandidateId[i] == candidateInfo[j].InnerText)
                    {
                        string noOfVotes = candidateInfo[j].Attributes["Votes"].Value;
                        int votes = int.Parse(noOfVotes);
                        votes--;
                        candidateInfo[j].Attributes["Votes"].Value = votes.ToString();
                        break;
                    }
                }
            }
            doc.Save(xmlFilePath);
        }
    }
}



